<?php
sleep(1);
defined('IN_PHPCMS') or exit('No permission resources.');
$db_picture = pc_base::load_model('picture_model');
$db_member = pc_base::load_model('member_model');
$db_picbuy = pc_base::load_model('picturebuy_records_model');
$spend = pc_base::load_app_class('spend','pay',0);

$id = isset($_GET['id'])?intval($_GET['id']):0;
$type = isset($_GET['type'])?intval($_GET['type']):1;
//判断是否登录
$phpcms_auth = param::get_cookie('auth');
$userid = param::get_cookie('_userid');
$username = param::get_cookie('_username');

if($phpcms_auth)
{
    get_pictrue();
}
else
{
    echo '{"status":"-1"}';
}


/**
 * 获指定图书价格信息
 * @param int $id
 * @param $userid
 */
function get_pictrue()
{
    global $db_picture,$db_picbuy,$db_member,$id,$userid,$username,$type;

    $query = 'SELECT p.id,p.title,d.price1,d.price2,d.price3 FROM `'.$db_picture->db_tablepre.'picture` p INNER JOIN `'.$db_picture->db_tablepre.'picture_data` d ON p.id = d.id WHERE p.id = '.$id.'  LIMIT 0,1';

    $res = $db_picture->query($query);
    $row = $db_picture->fetch_array();
	$count = count($row);

    if($count>0)
    {
        $price = $row[0]['price'.$type];
        if(!hasOrdered())
        {
            $rows = $db_member->get_one('userid='.$userid,'amount');
            if($rows['amount']<$price)
            {
                echo '{"price":"-2"}'; //余额不足返回-2
            }
            else
            {
                $data = array();
                $data['picture_id'] = $id;
                $data['user_id']    = $userid;
                $data['type']       = $type;

                $insert_id = $db_picbuy->insert($data,true);
                if($insert_id)
                {
                    $picture = $row[0]['title'];
                    switch($type)
                    {
                        case "1":
                            $picture = $picture.'_非商业用途';
                            break;
                        case "2":
                            $picture = $picture.'_商业用途';
                            break;
                        case "3":
                            $picture = $picture.'_版权图片';
                            break;
                    }
                    $flag = spend::amount($price,$picture,$userid,$username);
                    if($flag)
                    {
                        echo '{"price":"'.$row[0]['price'.$type].'","type":"'.$type.'"}';
                    }

                }
            }
        }
        else
        {
            echo '{"price":"-1"}'; //图书已经预定过返回-1
        }

    }

}

/**
 * 判断图片是否预订过
 * @param $id
 * @return bool
 */
function hasOrdered()
{
    global $db_picbuy,$id,$userid,$type;

    $where = array('picture_id'=>$id,'user_id'=>$userid,'type'=>$type);
    $res = $db_picbuy->get_one($where);
    if($res)
    {
        return true;
    }
    else
    {
        return false;
    }
}
?>